package pers.vic.practice.base.handler.json;

import com.fasterxml.jackson.core.JsonGenerator;
import org.springframework.stereotype.Component;
import pers.vic.boot.base.handler.json.BaseAppendJsonHandler;
import pers.vic.boot.base.handler.json.annotation.AppendJsonField;
import pers.vic.practice.base.constant.AppendJsonType;
import pers.vic.practice.module.system.model.SysDictType;
import pers.vic.practice.module.system.service.SysDictService;
import pers.vic.practice.module.system.service.SysDictTypeService;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 描述:字典类型 追加描述字典
 * @author Vic.xu
 * @date 2022-04-12 15:53
 */
@Component
public class DictTypeAppendJsonHandler extends BaseAppendJsonHandler {

    @Resource
    private SysDictTypeService sysDictTypeService;

    @Override
    protected void serialize(AppendJsonField appendJsonField, Object value, JsonGenerator gen) {
        if (value == null) {
            return;
        }
        String key = appendJsonField.key();
        String name = getValue(value + "");
        try {
            gen.writeStringField(key, name);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getValue(String value){
        String key =AppendJsonType.DICT_TYPE_CODE + value;
        String name = CacheAppendJson.get(key);
        if (name == null) {
            name =  sysDictTypeService.findByCode(value );
            CacheAppendJson.set(key, name);
        }
        return name;
    }

    @Override
    protected String type() {
        return AppendJsonType.DICT_TYPE_CODE;
    }
}
